package com.heima.user.interceptor;

import com.heima.common.Threadlocals.UserThreadLocalUtil;
import com.heima.common.dto.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: itheima
 * @create: 2022-05-16 10:45
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截（在调用Controller方法之前调用）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取从自媒体网关中转发来的请求 请求头中包含 APP用户ID userId
        String userId = request.getHeader("userId");
        String userName = request.getHeader("userName");
        String equipmentId = request.getHeader("equipmentId");
        if(StringUtils.isNotBlank(userId) && !userId.equals("0")){
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            user.setUserName(userName);
            //2.将用户信息存入ThreadLocal
            UserThreadLocalUtil.set(user);
        }else{
            User user = new User();
            user.setEquipmentId(equipmentId);
            //2.将用户信息存入ThreadLocal
            UserThreadLocalUtil.set(user);
        }
        return true;
    }

    /**
     * 后置拦截 （controller方法调用完毕）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocalUtil.remove();
    }
}
